package com.company.project.search.engine;

import com.alibaba.fastjson.JSONArray;
import com.company.project.search.entity.Search;
import com.company.project.search.util.OkHttpUtil;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 中国经济信息网
 * https://www.cei.cn
 */
@Component
public final class E6 extends AbstractE implements Callback {

    //?cursor=20首页不用cursor参数 从第二页起开始 cursor= 10
    private static final String url = "https://www.cei.cn/d/search/highSearch.action?cursor=";

    private static final Headers headers = new Headers.Builder()
            .add("Referer", "https://www.cei.cn/")
            .add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3")
            .add("Content-Type", "application/x-www-form-urlencoded")
            .add("Cache-Control", "no-cache")
            .add("Accept-Encoding", "gzip, deflate")
            .add("Accept-Language", "zh-CN,zh;q=0.9")
            .add("Cache-Control", "max-age=0")
            .add("Connection", "keep-alive")
            .add("Content-Length", "55")
            .add("Host", "www.cei.cn")
            .add("Upgrade-Insecure-Requests", "1")
            .add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36")
            .build();

    @Override
    public void search(Param p) {
        p.engine = Engine.ID_E6;
        RequestBody body = new FormBody.Builder()
                .add("keywords", p.keyword)
                .add("x", "37")
                .add("y", "13")
                .add("pageSize", "10")
                .add("currentMaxScore", "0.0")
                //activePage cuors 除以10
                .add("activePage", String.valueOf(p.curPage))
                .build();

        Request request = new Request.Builder()
                .url(url.concat(String.valueOf(p.curPage * 10)))
                .post(body)
                .headers(headers)
                .tag(p)
                .build();

        OkHttpUtil.getInstance().enqueue(request, this);
    }

    @Override
    public JSONArray provideCategory() {
        JSONArray list = new JSONArray();
        list.add(new Category("6-1", "中国经济网"));
        return list;
    }

    private void parse(Document html, Result result) {

        int total = 0;
        String totalStr = html.getElementsByClass("search_result_3").text();
        if (totalStr != null) {
            Pattern pattern = Pattern.compile("\\d+");
            Matcher matcher = pattern.matcher(totalStr);
            if (matcher.find()) {
                String g = matcher.group();
                if (g != null) {
                    try {
                        total = Integer.parseInt(g);
                    } catch (NumberFormatException ignored) {

                    }
                }
            }
        }

        Result.Header header = new Result.Header();
        header.engine = Engine.ID_E6;
        header.engineName = "中国经济网";
        header.maxPage = total / 20;
        header.totalCount = total;
        result.headers = new HashSet<>();
        result.headers.add(header);

        Elements searchList = html.getElementsByClass("search_list");

        if (searchList.size() != 1) return;

        Elements uls = html.getElementsByTag("li");
        List<Search> list = new ArrayList<>();
        result.list = list;

        if (!uls.isEmpty()) {
            Search tto;
            for (Element li : uls) {
                tto = Search.newInstance(Engine.ID_E6);
                Elements strong = li.getElementsByTag("strong");
                tto.setName(strong.get(0).getElementsByTag("a").text());
                tto.setAuthor("author:中国经济网");
                tto.setSource("source:中国经济网");
                tto.setCategory("6-1");
                tto.setUrl(strong.get(0).getElementsByTag("a").attr("href"));
                String date = li.getElementsByClass("span").text();
                tto.setPublishDate(date);
                tto.setTotal(total);
                list.add(tto);
            }
        }
        if (callback != null) callback.callback(result);
    }

    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        System.out.println("E6响应失败");
    }

    @Override
    public void onResponse(@NotNull Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String html = responseBody.string();
                Param p = (Param) call.request().tag();
                if (p != null) System.out.println("E6响应成功:" + (System.currentTimeMillis() - p.duration) + "ms");
                Result result = new Result(p);
                parse(Jsoup.parse(html), result);
            }
        }
    }

    private static final class Holder {
        private static final AbstractE ins = new E6();
    }

    private E6() {

    }

    public static AbstractE getInstance() {
        return Holder.ins;
    }
}
